package cc.togetherit.jcrawler.util;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
// import org.apache.log4j.//logger;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

/**
 * 获取HTTPCleaner 对象
 * 
 * @author lileigang 2014年10月29日 下午2:26:12
 */
public class HtmlCleanerUtil {
    public static String simpleFormat = "yyyy-MM-dd HH:mm:ss";
    // private static //logger //logger = //logger.get//logger(HtmlCleanerUtil.class);
    private static HtmlCleaner cleaner = null;
    private static HtmlCleanerUtil instance = new HtmlCleanerUtil();
    private Map<String, String> monthMap = new HashMap<String, String>();

    private HtmlCleanerUtil() {
        cleaner = new HtmlCleaner();
        monthMap.put("JANUARY", "01");
        monthMap.put("FEBRUARY", "02");
        monthMap.put("MARCH", "03");
        monthMap.put("APRIL", "04");
        monthMap.put("MAY", "05");
        monthMap.put("JUNE", "06");
        monthMap.put("JULY", "07");
        monthMap.put("AUGUST", "08");
        monthMap.put("SEPTEMBER", "09");
        monthMap.put("OCTOBER", "10");
        monthMap.put("NOVEMBER", "11");
        monthMap.put("DECEMBER", "12");

        monthMap.put("JAN", "01");
        monthMap.put("FEB", "02");
        monthMap.put("MAR", "03");
        monthMap.put("APR", "04");
        monthMap.put("MAY", "05");
        monthMap.put("JUN", "06");
        monthMap.put("JUL", "07");
        monthMap.put("AUG", "08");
        monthMap.put("SEP", "09");
        monthMap.put("OCT", "10");
        monthMap.put("NOV", "11");
        monthMap.put("DEC", "12");


    }

    public static HtmlCleanerUtil getInstance() {
        synchronized (instance) {
            if (instance == null) {
                instance = new HtmlCleanerUtil();
            }
        }

        return instance;
    }


    public Object[] parseObjectByTag(TagNode tag, String evluatePath) {

        Object[] res = null;
        try {

            res = tag.evaluateXPath(evluatePath);

        } catch (Exception e) {
            // System.out.println("******parser tag error***********");
            // logger.error("parseTagurl", e);//e.printStackTrace();
        }

        return res;
    }

    public TagNode[] parseTagNodeArrayByTag(TagNode tag, String evluatePath) {

        Object[] res = null;

        List<TagNode> result = null;
        try {
            result = new ArrayList<TagNode>();
            res = tag.evaluateXPath(evluatePath);
            if (res != null && res.length > 0) {
                for (Object o : res) {
                    if (o instanceof TagNode) {
                        result.add((TagNode) o);
                    }
                }
            }



        } catch (Exception e) {
            // System.out.println("******parser tag error***********");
            // logger.error("parseTagurl", e);//e.printStackTrace();
        }
        TagNode[] resa = new TagNode[result.size()];
        return result.toArray(resa);
    }


    // get tag text
    public String parserTextByTag(TagNode tag, String evluatePath) {

        String res = "";
        try {

            Object[] obj = tag.evaluateXPath(evluatePath);
            if (obj.length > 0) {
                CharSequence sb = ((TagNode) obj[0]).getText();
                if (sb != null)
                    res = sb.toString();
            }

        } catch (Exception e) {
            // System.out.println("******parser tag error***********");
            // logger.error("parseTagurl", e);//e.printStackTrace();
        }

        return res;
    }

    // get tag property value
    public String parserAttrByTag(TagNode tag, String attrName, String attrValue, String attrProperty) {

        String res = "";
        try {

            Object[] obj = tag.getElementsByAttValue(attrName, attrValue, true, true);
            if (obj.length > 0) {
                res = ((TagNode) obj[0]).getAttributeByName(attrProperty);

            }

        } catch (Exception e) {
            // logger.error("parserAttrByTag", e);//e.printStackTrace();
        }

        return res;
    }

    public TagNode[] parserAttrsByTag(TagNode tag, String attrName, String attrValue) {


        Object[] res = null;

        List<TagNode> result = null;
        try {
            result = new ArrayList<TagNode>();
            res = tag.getElementsByAttValue(attrName, attrValue, true, true);
            if (res != null && res.length > 0) {
                for (Object o : res) {
                    if (o instanceof TagNode) {
                        result.add((TagNode) o);
                    }
                }
            }

        } catch (Exception e) {
            // System.out.println("******parser tag error***********");
            // logger.error("parseTagurl", e);//e.printStackTrace();
        }
        TagNode[] resa = new TagNode[result.size()];
        return result.toArray(resa);

    }

    public String parserAttrsByTag(TagNode tag, String attrName, String attrValue, String attrProperty) {

        String res = "";
        try {

            Object[] obj = tag.getElementsByAttValue(attrName, attrValue, true, true);
            if (obj.length > 0) {
                res = ((TagNode) obj[0]).getAttributeByName(attrProperty);

            }

        } catch (Exception e) {
            // logger.error("parserAttrByTag", e);//e.printStackTrace();
        }

        return res;
    }



    public String parserAttrByTag(TagNode tag, String tagName, String attrName) {
        String res = "";
        try {
            Object[] obj = tag.getElementsByName(tagName, true);
            if (obj.length > 0) {
                res = ((TagNode) obj[0]).getAttributeByName(attrName);
            }

        } catch (Exception e) {
            // logger.error("parserAttrByTag", e);
        }

        return res;
    }



    // get tag property value
    public String parserAttrByXpath(TagNode tag, String evluatePath, String attrProperty) {

        String res = "";
        try {

            Object[] obj = tag.evaluateXPath(evluatePath);
            if (obj.length > 0) {
                res = ((TagNode) obj[0]).getAttributeByName(attrProperty);

            }

        } catch (Exception e) {
            // logger.error("parserAttrByTag", e);//e.printStackTrace();
        }

        return res;
    }


    public TagNode getHtmlTag(String content) {
        if (StrUtil.isNull(content)) {
            return null;
        }
        TagNode tag = cleaner.clean(content);
        return tag;
    }

    public String patternStr(String content, String regex) {
        if (content == null)
            return "";
        String res = "";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        content = null;
        if (m.find()) {
            if (m.group() != null)
                res = m.group(1);
        }

        return res;
    }


    public boolean isNumber(String str) {
        if (str == null || str.trim().length() == 0)
            return false;

        String regex = "^[0-9]*$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }

        return false;
    }

    public String getNumMonth(String enMonth) {
        String s = "";
        s = monthMap.get(enMonth.toUpperCase());
        if (StringUtils.isEmpty(s)) {
            return "";
        }
        return s;

    }

    public String getDate(Date date, String type, int mount, String dateFormat) {
        DateFormat df = new SimpleDateFormat(dateFormat);
        type = type.toLowerCase();
        if (StringUtils.contains(type, "min")) {
            return df.format(DateUtils.addMinutes(date, mount));

        }
        if (StringUtils.contains(type, "hour")) {
            return df.format(DateUtils.addHours(date, mount));

        }
        if (StringUtils.contains(type, "day")) {
            return df.format(DateUtils.addDays(date, mount));

        }
        if (StringUtils.contains(type, "month")) {
            return df.format(DateUtils.addMonths(date, mount));

        }
        if (StringUtils.contains(type, "week")) {
            return df.format(DateUtils.addWeeks(date, mount));

        }
        if (StringUtils.contains(type, "year")) {
            return df.format(DateUtils.addYears(date, mount));

        }
        return "";
    }

    public String[] parsePeriodStr(String periodStr) {
        if (StringUtils.contains(periodStr, "hour")) {
            return new String[] {periodStr.split("hour")[0], "hour"};

        }
        if (StringUtils.contains(periodStr, "day")) {
            return new String[] {periodStr.split("day")[0], "day"};

        }
        if (StringUtils.contains(periodStr, "month")) {
            return new String[] {periodStr.split("month")[0], "month"};

        }
        if (StringUtils.contains(periodStr, "week")) {
            return new String[] {periodStr.split("week")[0], "week"};

        }
        if (StringUtils.contains(periodStr, "year")) {
            return new String[] {periodStr.split("year")[0], "year"};

        }
        return new String[] {"", ""};

    }

    public String getSimpleFromat() {
        return simpleFormat;
    }

}
